import { InputNumber } from "antd";
import { CloseCircleFilled } from "@ant-design/icons";
import { isNil } from "lodash";
import { useEffect, useState } from "react";
import Typography from "../Typography";
import Style from "./index.module.less";

function CommonInputNumber(props) {
	const { placeholder, max, allowClearProps, ...arg } = props;
	const [isShowPlaceholder, setIsShowPlaceholder] = useState(isNil(arg.value));

	const [keyDownInput, setKeyDownInput] = useState("");

	useEffect(() => {
		setIsShowPlaceholder(isNaN(arg.value));
		setKeyDownInput(arg.value || "");
	}, [arg.value]);

	const { fieldName, allowClear, resetValue, validateValue } = allowClearProps || {};
	// 点击清除
	const onSuffixClick = () => {
		resetValue({ [fieldName]: null })
		validateValue([fieldName])
		setKeyDownInput('')
		const element = document.getElementById(fieldName);
		element.focus();
	}

	return (
		<div className={Style["c-input-number-wrapper"]}>
			<InputNumber
				controls={false}
				max={max || 100000000}
				{...arg}
				onInput={v => {
					setKeyDownInput(v);
				}}
				onChange={v => {
					arg.onChange && arg.onChange(v);
				}}
				onBlur={v => {
					//   setKeyDownInput('');
					arg.onBlur && arg.onBlur(v);
				}}
				id={fieldName}
			></InputNumber>
			{/* 清除图标 */}
			{ allowClear && keyDownInput && <CloseCircleFilled  onClick={onSuffixClick}/>}

			{placeholder && !keyDownInput && (isShowPlaceholder || isNil(arg.value)) && (
				<div className={Style["ant-input-placeholder"]}>
					{!!arg["aria-required"] && <Typography type="error">*</Typography>}
					{placeholder}
				</div>
			)}
		</div>
	);
}
export default CommonInputNumber;
